package com.alog.storage.domain;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class ViewHolder {
    private SparseArray<View> mViews;
    private View mConvertView;
    public int groupPosition;
    public int childPosition;

    private ViewHolder(Context context, ViewGroup parent, int layoutId, int... position) {
        this.mViews = new SparseArray<View>();
        mConvertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
        mConvertView.setTag(this);
        if (position != null) {
            if (position.length == 1) {
                this.groupPosition = position[0];
            } else if (position.length == 2) {
                this.groupPosition = position[0];
                this.childPosition = position[1];
            }
        }
    }

    /**
     * 获取当前CommonViewHolder
     */
    public static ViewHolder get(Context context, View convertView, ViewGroup parent, int layoutId, int... position) {
        if (convertView == null) {
            return new ViewHolder(context, parent, layoutId, position);
        }
        return (ViewHolder) convertView.getTag();
    }

    public View getConvertView() {
        return mConvertView;
    }

    /**
     * 通过控件的Id获取控件，没有则查找并加入views
     */
    public <T extends View> T getView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    /**
     * 为TextView设置显示内容
     */
    public TextView setText(int viewId, String text) {
        TextView view = getView(viewId);
        view.setText(text);
        return view;
    }

    /**
     * 为ImageView设置显示图片
     */
    public ImageView setImageResource(int viewId, int drawableId) {
        ImageView view = getView(viewId);
        view.setImageResource(drawableId);
        return view;
    }

    /**
     * 为ImageView设置显示图片
     */
    public ImageView setImageBitmap(int viewId, Bitmap bmp) {
        ImageView view = getView(viewId);
        view.setImageBitmap(bmp);
        return view;
    }

}
